package cn.jkgly.demo.service;

import cn.jkgly.demo.Helper.Https;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.RandomStringUtils;


import java.io.IOException;
import java.util.Arrays;


public class JsapiTicketUtil {

    public static JSONObject getWXConfigSignature() {
        String appid="wx3a06c113295b44c3";
        long timeStampSec = System.currentTimeMillis() / 1000;
        String timestamp = String.format("%010d", timeStampSec);
        String nonceStr = RandomStringUtils.randomAlphanumeric(8);
        JSONObject respJson = new JSONObject();
        String wxJsapiTicket = getWXJsapiTicket();
        String[] signArr = new String[]{ "jsapi_ticket=" + wxJsapiTicket, "noncestr=" + nonceStr, "timestamp=" + timestamp};
        Arrays.sort(signArr);
        String signStr = String.join("&",signArr);
        String resSign = DigestUtils.sha1Hex(signStr);
        respJson.put("appId", appid);
        respJson.put("timestamp", timestamp);
        respJson.put("nonceStr", nonceStr);
        respJson.put("signature", resSign);

        return respJson;
    }

    public static String getWXJsapiTicket() {
        String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + getWXaccessToken() + "&type=jsapi";
        String tickets= null;
        try {
            tickets = Https.https(url,"GET");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return JSONObject.parseObject(tickets).getString("ticket");
    }

    private static String getWXaccessToken()  {
        String appid="wx3a06c113295b44c3";
        String secret="4d0807797b51489dc3be77bac85c9e79";
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appid+"&secret="+secret;
        String token= null;
        try {
            token = Https.https(url,"GET");
            System.out.println(token);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return JSONObject.parseObject(token).getString("access_token");
    }
   public static void main(String[] args){
       String token= getWXaccessToken();
       System.out.println(token);
   }
}
